import Taro from '@tarojs/taro';

import { Command } from '../constant';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';

import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async page() {
      let { ReleasedTab, ReceivingTab, orderType } = getData().main;
      const { inService, waitDeal } = await api.escortTradeController.getEscorttradeCount();
      const EscortsnatchorderCount = await api.escortTradeController.getEscortsnatchorderCount();
      ReleasedTab[1].num = waitDeal;
      ReleasedTab[2].num = inService;
      ReceivingTab[1].num = EscortsnatchorderCount;
      action.commonChange('main.ReleasedTab', ReleasedTab);
      action.commonChange('main.ReceivingTab', ReceivingTab);
      if (orderType == 1) {
        //分页查询发布的配送订单(我的发布)
        action.findMyEscorttradeList();
      } else {
        //分页查询我的接单(我的接单)
        action.findEscortsnatchorderList();
      }
    },

    async findMyEscorttradeList() {//分页查询发布的配送订单(我的发布)
      let shopUser = JSON.parse(Taro.getStorageSync('b2b-wechat@login').shopUser);
      let selectDistance = Taro.getStorageSync('selectDistance');
      let { pageNum, pageSize, orderList, escortTradeStatus } = getData().main;
      const params = {
        // communityId: selectDistance?.id,//社区id
        // courierStationId: 0,//驿站id
        // courierStationName: '',//驿站名称
        // customerId: shopUser.context.customerId,
        // escortTradePay: 0,//支付方式，0：微信支付，1：余额支付，2：积分支付，3：积分+微信，4：积分+余额
        // escortTradePayStatus: '',//配送订单的支付状态，0：未付款，1：已付款，2：已退款
        escortTradeStatus,//订单状态，0：待支付，1：待接单，2：服务中，3：已完成，4：已取消
        pageNum,//第几页
        pageSize,//每页显示多少条
      };
      const result = await api.escortTradeController.findMyEscorttradeList(params);
      if (result.code == 'K-000000') {
        this.commonChange('main.totalPages', result.context.totalPages);
        if (pageNum == 0) {
          action.commonChange('main.orderList', result.context.content)
        } else {
          let newList = orderList.concat(
            result.context.content,
          );
          action.commonChange('main.orderList', newList)
        }
      } else {
        Taro.showToast({
          title: result.context,
          icon: 'none',
          duration: 2000,
        });
      }
    },

    async findEscortsnatchorderList() {//分页查询我的接单(我的接单)
      let shopUser = JSON.parse(Taro.getStorageSync('b2b-wechat@login').shopUser);
      let selectDistance = Taro.getStorageSync('selectDistance');
      let { pageNum, pageSize, orderList, escortSnatchOrderStatus } = getData().main;
      const params = {
        communityId: selectDistance?.id,//社区id
        // courierStationId: 0,//驿站id
        // courierStationName: '',//驿站名称
        customerId: shopUser.context.customerId,
        escortSnatchOrderStatus,//接单状态，0：服务中，1：已完成
        pageNum,//第几页
        pageSize,//每页显示多少条
        // snatchImg: '',//凭证图片
      };
      const result = await api.escortTradeController.findEscortsnatchorderList(params);
      if (result.code == 'K-000000') {
        this.commonChange('main.totalPages', result.context.totalPages);
        if (pageNum == 0) {
          action.commonChange('main.orderList', result.context.content)
        } else {
          let newList = orderList.concat(
            result.context.content,
          );
          action.commonChange('main.orderList', newList)
        }
      } else {
        Taro.showToast({
          title: result.context,
          icon: 'none',
          duration: 2000,
        });
      }
    },

    async harvestCode() {//确认完成核销码校验
      let { user } = Taro.getStorageSync('b2b-wechat@login');
      let shopUser = JSON.parse(Taro.getStorageSync('b2b-wechat@login').shopUser);
      let { escortTradeId, harvestCode } = getData().main;
      const params = {
        customerId: shopUser.context.customerId,
        escortTradeId,//订单id
        harvestCode,//收货编码
      };
      const result = await api.escortTradeController.harvestCode(params);
      action.commonChange('main.harvestCode', '')
      if (result.code == 'K-000000') {
        Taro.showToast({
          title: '已核销',
          icon: 'none',
          duration: 2000,
        });
        action.commonChange('main.pageNum', 0);
        action.page()
      } else {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 2000,
        });
      }
    },

    async delEscortsnatchorderDetail(id) {//删除我的接单
      const result = await api.escortTradeController.delEscortsnatchorderDetail(id);
      if (result.code == 'K-000000') {
        Taro.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000,
        });
        action.commonChange('main.pageNum', 0);
        action.page()
      } else {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 2000,
        });
      }
    },

    async delEscorttradeDetail(id) {//删除我的发单
      const result = await api.escortTradeController.delEscorttradeDetail(id);
      if (result.code == 'K-000000') {
        Taro.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000,
        });
        action.commonChange('main.pageNum', 0);
        action.page()
      } else {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 2000,
        });
      }
    },

    async cancelEscorttrade() {//取消订单
      let { escortTradeId, cancellationOptions, cancellationReason } = getData().main;
      let params = {
        cancellationOptions,//配送订单取消选项
        cancellationReason,//配送订单取消原因
        id: escortTradeId,//订单id
      }
      const result = await api.escortTradeController.cancelEscorttrade(params);
      if (result.code == 'K-000000') {
        Taro.showToast({
          title: '取消成功',
          icon: 'none',
          duration: 2000,
        });
        action.commonChange('main.pageNum', 0);
        action.commonChange('main.cancelModel', false)
        action.page()
      } else {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 2000,
        });
      }
    },

    async statistics() {
      const { accountBalanceTotal } = await api.customerDrawCashController.statistics();
      action.commonChange('main.accountBalanceTotal', accountBalanceTotal)
    }
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageLifeOrdersDMain'),
  };
}
